import Taro, {Component} from '@tarojs/taro'
import Envs from '../../../constant/envs'
import {View,Picker} from "@tarojs/components"
import { AtTabs, AtTabsPane, AtInput, AtForm ,AtButton,AtMessage,AtList, AtListItem } from 'taro-ui'
import {getGlobalData,setGlobalData} from "../../../global.d";
import {getLocation, toast} from "../../../utils/index";
import {addNewSign} from './service'
import './index.scss'
import {getClassByClassKey} from "../../../service";
const chooseLocation = Taro.requirePlugin('chooseLocation');
export default class Index extends Component {
  config = {
    enablePullDownRefresh:true
  }
    constructor(props) {
        super(props);
        this.state = {
            current: 0,
            user:{},
            name:'',
            startTime:'',
            endTime:'',
            addressName:'',
            address:'',
            latitude:'',
            longitude:'',
            signList:[],
          stuInfo:{}
        }
    }
  componentWillMount(){
      let user = getGlobalData('user')
    this.setState({
      user
    })
  }
  componentDidMount () {
    Taro.setNavigationBarTitle({
      title:'签到'
    })
    this.getList()
   this.setState({
     startTime:this.getTime(),
     endTime:this.getTime(15)
   })
    this.getClassStu()
  }

  componentDidShow() {

      const location = chooseLocation.getLocation();
      if (!location) return
      const {name,address,longitude,latitude} = location
      console.log(location)
      this.setState({
        addressName:name,
        address,
        longitude,
        latitude
      })
  }
  onPullDownRefresh(){
    this.getList()
  }

  handleClick (value) {
    if(this.state.user.userLastTimeClass.type!=='admin'){
      toast('只有管理员可以发布签到哟')
      return
    }
    this.setState({
      current: value
    })
  }
  handleChange(key, val) {
    this.setState({
      [key] : val
    });
    return val
  }
  onTimeChange (key,e){
    this.setState({
      [key] : e.detail.value
    });
  }
  getTime(plus=0){
      const date = new Date()
    date.setMinutes(date.getMinutes()+plus)
    const hour = date.getHours();
    const minute = date.getMinutes();
    return hour+":"+minute
  }

  choosePoint(){
      getLocation().then(res=>{
        const { longitude, latitude } = res
        this.setState({
          longitude,
          latitude
        })
        this.callPlugin({
          latitude,
          longitude})
      })
  }

  callPlugin(locat){
    const key = 'K6TBZ-7B3RP-MGSDJ-V7KPA-AT532-QAB4I'; //使用在腾讯位置服务申请的key
    const referer = '酷班级'; //调用插件的app的名称
    const location = JSON.stringify(locat);
    const category = '大学,机构团体,文化场馆';

    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
    });
  }
 async addSign(){
      const {name,addressName,longitude,latitude,address,startTime,endTime,stuInfo} = this.state
      if(!name){
        Taro.showToast({
          title: '请填写签到名称',
          icon: 'none',
        })
        return
      }
    if(!addressName){
      Taro.showToast({
        title: '请填写签到地点',
        icon: 'none',
      })
      return
    }
    let startTime1 = new Date()
    let endTime1 = new Date()
   startTime1.setHours(startTime.split(':')[0],startTime.split(':')[1])
   endTime1.setHours(endTime.split(':')[0],endTime.split(':')[1])

 let result = await  addNewSign({
      name,
      startTime:startTime1,
      endTime:endTime1,
      address,
      addressName,
      longitude,
      latitude,
      belongClass:this.state.user.userLastTimeClass.classKey,
      stuInfo,
      status:''
    })
   if(result) {
      this.setState({
        current:0,
        name:'',
        addressName:'',
        address:'',
        longitude:'',
        latitude:''
      })
      Taro.startPullDownRefresh()
      this.getList()
   }

  }

  getList(){
    Taro.cloud.callFunction({
      name:'getSignList',
      data:{
        classKey:this.state.user.userLastTimeClass.classKey,
        env:Envs.current
      }
    })
      .then(res=>{
        let signList = res.result.data
        signList.reverse()
        const date = new Date()
        const time = date.getTime()
        signList = signList.map((item,index)=>{
          item.startTime = new Date(item.startTime)
          item.endTime = new Date(item.endTime)
          if(item.endTime.getTime()<time){
            item.status = '已结束'
          } else if(item.startTime.getTime()>time){
            item.status = '未开始'
          }else {
            item.status = '进行中'
          }
          return item
        })
        this.setState({
          signList
        })
        Taro.stopPullDownRefresh()
      })
  }

 async getClassStu(){
    const result = await getClassByClassKey(this.state.user.userLastTimeClass.classKey)
   console.log(result)
   const stu  = result.classStudents.concat(result.classAdmins)
   console.log(stu)
   let signStu = []
    stu.forEach((item,index)=>{
      signStu.push({
        _id:item._id,
        signTime:'',
        name:item.userDetail.userRealName,
        avatarUrl:item.userInfo.avatarUrl,
        signed: false
      })
    })
   this.setState({
     stuInfo:signStu
   })
  }

  navigateToSignDetail(id){
  Taro.navigateTo({
    url:`/pages/tools/sign/signDetail/index?id=${id}`
  })
  }



    render() {
      const tabList = [{ title: '我的签到' }, { title: '发布签到' }]
      const {name,longitude,latitude,address,addressName} = this.state
      const list = this.state.signList.map((item,index)=>{
        return    <AtListItem
            arrow='right'
            note={item.addressName}
            title={item.name}
            extraText={item.status}
            onClick={this.navigateToSignDetail.bind(this,item._id)}
          />
      })
      const noSign = <View className="noSign">
        暂时没有签到哟(＾Ｕ＾)ノ~ＹＯ
      </View>
        return (
            <View>
              <AtTabs current={this.state.current} tabList={tabList} onClick={this.handleClick.bind(this)}>
                <AtTabsPane current={this.state.current} index={0} >
                  <View>
                    <AtList>
                      {this.state.signList.length===0?noSign:list}
                    </AtList>
                  </View>
                </AtTabsPane>
                <AtTabsPane current={this.state.current} index={1}>
                  <View >
                    <AtForm>
                      <AtInput
                        name='name'
                        title='签到名称'
                        type='text'
                        placeholder='*必填（如：班会签到）'
                        value={name}
                        onChange={this.handleChange.bind(this,'name')}
                      >
                      </AtInput>
                      <Picker mode='time' onChange={this.onTimeChange.bind(this,'startTime')}>
                        <AtInput
                          title='开始时间'
                          value={this.state.startTime}
                        >
                        </AtInput>
                      </Picker>
                      <Picker mode='time'
                              start={this.state.startTime}
                              onChange={this.onTimeChange.bind(this,'endTime')}>
                        <AtInput
                          title='结束时间'
                          value={this.state.endTime}
                        >
                        </AtInput>
                      </Picker>
                      <View>
                        {
                          !latitude&&
                          <View >
                          <AtButton
                          type='secondary'
                          onClick={this.choosePoint.bind(this)}
                          full={false}
                          >选择签到地点</AtButton>
                          </View>
                        }
                        {
                          latitude&&
                          <View>
                            <AtInput
                              name='addressName'
                              title='地点名称'
                              type='text'
                              value={addressName}
                              onChange={this.handleChange.bind(this,'addressName')}
                            >
                            </AtInput>
                            <AtInput
                              name='address'
                              title='地址'
                              type='text'
                              value={address}
                              onChange={this.handleChange.bind(this,'address')}
                            >
                            </AtInput>
                            <AtInput
                              disabled
                              name='longitude'
                              title='经度'
                              type='text'
                              value={longitude}
                              onChange={this.handleChange.bind(this,'longitude')}
                            >
                            </AtInput>
                            <AtInput
                              disabled
                              name='latitude'
                              title='维度'
                              type='text'
                              value={latitude}
                              onChange={this.handleChange.bind(this,'latitude')}
                            >
                            </AtInput>
                            <View className="margin-50">
                              <AtButton
                                type='secondary'
                                onClick={this.choosePoint.bind(this)}
                                full={false}
                                className="addressButton"
                              >重新选择地点</AtButton>
                              <AtButton
                                type='primary'
                                onClick={this.addSign.bind(this)}
                                full={false}
                                className="submitButton"
                              >发起签到</AtButton>
                            </View>
                          </View>

                        }

                      </View>
                    </AtForm>
                  </View>
                </AtTabsPane>
              </AtTabs>
            </View>
        )
    }

}
